﻿using AutoMapper;
using DongFangGuoKai.WMS.IApiService;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Domain.TMSModels;
using DongFangGuoKai.WMSPlatform.Service.CabinetApp.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration;

namespace DongFangGuoKai.WMSPlatform.Service.CabinetApp
{
    public  partial class CabinetService : ICabinetService
    {
        public CabinetService(
            WMSPlatformContext context,
            ITMSService tmsHttp,
            IMapper mapper,
            ILogger<CabinetService> logger,
            IConfiguration configuration
           )
        {
            TMSHttp = tmsHttp;
            Mapper = mapper;
            Context = context;
            Configuration = configuration;
            Logger = logger;

        }
        public ITMSService TMSHttp { get; }
        public WMSPlatformContext Context { get; }
        public IMapper Mapper { get; }
        public ILogger<CabinetService> Logger { get; }
        public IConfiguration Configuration { get; }

        /// <summary>
        /// 分配窗格  
        /// 读取配置文件，根据优先级来分配窗口，插入TCabinetCellTemp实时分配窗口表
        /// </summary>
        /// <param name="msg">错误消息</param>
        /// <param name="allocationPositionDto">分配窗口所需参数</param>
        /// <returns></returns>
        public bool AllocationPosition(out string msg, out string data, AllocationPositionDto allocationPositionDto)
        {
            msg = string.Empty;
            data = "";
            bool result = false;
            Guid guid = Guid.NewGuid();
            string cabinetLocationCode = "";
            string cabinetLocationName = "";
            var allocationPositionList = Configuration.GetSection("CabinetLocationCodeS").Get<List<CabinetLocationCodeDto>>();
            if (allocationPositionList == null || allocationPositionList.Count == 0)
            {
                msg = "未读取机柜点位编码";
                return false;
            }
            try
            {
                BoxResultResoons<BoxResponsData>? httpRespons = null;
                foreach (var item in allocationPositionList.OrderBy(o => o.Priority))
                {
                    BoxOrderModel model = new BoxOrderModel()
                    {
                        boxType = allocationPositionDto.type.ToString(),
                        cabinetLocationCode = item.CabinetLocationCode,
                        orderNo = guid.ToString()
                    };

                    httpRespons = TMSHttp.OpenBox(model);

                    if (!httpRespons.success)
                    {
                        Logger.LogError(httpRespons.ToJson());
                        result = false;
                        continue;
                    }
                    cabinetLocationCode = item.CabinetLocationCode;
                    cabinetLocationName = item.CabinetLocationName;
                    result = true;
                    break;

                }
                if (!result)
                {
                    msg = $"窗格分配失败：" + httpRespons?.message;
                    return false;
                }
                var cabinetCell = Context.CabinetCellTemps.FirstOrDefault(t => t.CabinetLocationCode == httpRespons.data.cabinetLocationCode && t.CabinetBoxId == httpRespons.data.cabinetBoxId);
                if (cabinetCell == null)
                {
                    cabinetCell = new TCabinetCellTemp()
                    {
                        CabinetLocationCode = cabinetLocationCode,
                        CabinetLocationName = cabinetLocationName,
                        CellSizeType = allocationPositionDto.type,
                        BoxLabel = httpRespons?.data.boxLabel,
                        CabinetBoxId = httpRespons?.data.cabinetBoxId,
                        TaskCode = guid,
                        Code = cabinetLocationCode + "_" + httpRespons?.data.cabinetBoxId + "_" + allocationPositionDto.type,
                        Name = cabinetLocationName + "柜" + httpRespons?.data.cabinetBoxId + "号" + allocationPositionDto.type + "类型",
                        CreateDate = DateTime.Now,
                        CreateUserId = 1,
                        CreateUserName = "admin",
                        Status = 1
                    };

                    Context.CabinetCellTemps.Add(cabinetCell);
                }
                else
                {
                    cabinetCell.TaskCode = guid;
                    cabinetCell.ModifyDate = DateTime.Now;
                    cabinetCell.ModifyUserId = 1;
                    cabinetCell.ModifyUserName = "admin";
                    cabinetCell.Status = 1;
                    Context.CabinetCellTemps.Update(cabinetCell);
                }
                Context.SaveChanges();
                msg = $"分配成功：" + cabinetCell.Name;
                data = guid.ToString();
                return true;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                msg = ex.Message;
                return false;
            }

        }

        public bool CabinetClose(out string msg, Guid guid)
        {
            msg = string.Empty;
            bool result = false;

            Context.Database.BeginTransaction();
            var cell = Context.CabinetCellTemps.FirstOrDefault(t => t.TaskCode == guid);
            if (cell == null)
            {
                Context.Database.RollbackTransaction();
                msg = $"流水：{guid}，未找到记录 ";
                return false;
            }
            //入库
            if (cell.Status == 1)
            {

            }
            else if (cell.Status == 2)  //出库
            {

            }


            return true;
        }



    }
}
